var util = require('../../utils/util.js');
var WXBizDataCrypt = require('../../crypto/WXBizDataCrypt.js');
let app = getApp();
let url = app.url;
let gobalData = app.gobalData;
let QR = require("../../utils/qrcode.js");
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		userName: '',
		userAvatar: '',
		cid: 0,
    QRCode: "https://zxe-dev.bajiaostar.com",
		height: 0
	},
	// 分享给好友或朋友圈
	onShareAppMessage(res){
    return {
      title: '装笆，您的专属监理专家',
      path: `pages/supervisionSiteTwo/index?leaderId=${this.data.cid}`
    }
	},
  //适配不同屏幕大小的canvas
  setCanvasSize:function(){
    var size={};
    try {
        var res = wx.getSystemInfoSync();
        var scale = 750/686;//不同屏幕下canvas的适配比例；设计稿是750宽
        var width = res.windowWidth/scale;
        var height = width;//canvas画布为正方形
        size.w = width;
        size.h = height;
				this.setData({
					height: res.screenHeight
				})
      } catch (e) {
        // Do something when catch error
      } 
    return size;
  },
	createQrCode:function(url,canvasId,cavW,cavH){
		//调用插件中的draw方法，绘制二维码图片
		QR.api.draw(url,canvasId,cavW,cavH);
		setTimeout(() => { this.canvasToTempImage();},1000);
		
	},
	//获取临时缓存照片路径，存入data中
	canvasToTempImage:function(){
		var that = this;
		wx.canvasToTempFilePath({
			canvasId: 'sharePoster',
			success: function (res) {
					var tempFilePath = res.tempFilePath;
					that.setData({
						QRCode:tempFilePath,
					});
			},
			fail: function (res) {
			}
		});
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		
		this.setData({
			userName: wx.getStorageSync('userInfo').userInfo.name,
			userAvatar: wx.getStorageSync('userInfo').userInfo.avatar,
			cid: wx.getStorageSync('userInfo').userInfo.id
		})
		let self = this;
		wx.downloadFile({
			url: this.data.userAvatar,
			success(res){
				self.setData({
					userAvatar: res.tempFilePath
				})
			}
		})
		// 页面初始化 options为页面跳转所带来的参数
		var size = this.setCanvasSize();//动态设置画布大小
		var initUrl = this.data.QRCode + '/?cid=' + this.data.cid;
    console.log(initUrl);
		this.createQrCode(initUrl, "sharePoster", size.w, size.h);
	},
	// 绘制画布
	upPoster() {
		let self = this;
		// 创建画布实例
		let ctx = wx.createCanvasContext('sharePoster-two');
		// 先清除，再重画一次
		ctx.clearRect(0, 0, 0, 0);
		// 添加背景图片
		ctx.drawImage('/assets/image/poster/img.jpg', 0, 0, 375, 304);
		// 绘制头像
		ctx.save();
		ctx.beginPath();
		let r = 35;
		let d = r * 2;
		let cx = 150;
		let cy = 75;
		ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
		ctx.closePath();
		ctx.clip();
		ctx.drawImage(self.data.userAvatar, cx, cy, d, d);
		ctx.restore(); //恢复之前保存的绘图上下文。(不写下面文字显示不出来)
		// 绘制昵称
		ctx.setFontSize(14);
		ctx.setFillStyle('#fff');
		ctx.setTextAlign('center')
		ctx.fillText(self.data.userName, 182, 170);
		ctx.fillText('成功在 装笆 报名了监理服务', 182, 200);
		ctx.setFillStyle('#fff');
		ctx.fillRect(0, 304, 375, this.data.height);
		// 绘制小程序二维码
		ctx.drawImage(self.data.QRCode, 100, 340, 181, 181);
		ctx.setFontSize(20);
		ctx.setFillStyle('#fa863b');
		ctx.setTextAlign('center')
		ctx.fillText('装笆，您的专属监理专家~', 192, 550);
		// 结束绘画
		ctx.draw();
	},
	// 生成海报
	buildPoster() {
		wx.showToast({
			title: '海报生成中...',
			icon: 'loading',
			duration: 2000
		})
		this.upPoster();
		//保存图片至相册
		let that = this;
		setTimeout(function() {
			wx.canvasToTempFilePath({
				x: 0,
				y: 0,
				width: 375,
				height: 650,
				destWidth: 750,
				destHeight: 1200,
				quality: 1,
				canvasId: 'sharePoster-two',
				fileType: 'jpg',
				success: function(res) {
					wx.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success(res) {
							wx.hideLoading();
							wx.showToast({
								title: '保存成功',
							});
						},
						fail(err) {
							console.log(err)
							wx.hideLoading()
							if (err.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
								console.log('重新拉取授权')
								wx.openSetting({
									success(res) {
										console.log(res)
									}
								})
							}
						}
					})
				}
			})
		}, 1000);
	}
})
